package com.tairanchina.md.meeting.resource;

import com.tairanchina.md.constants.CommonConstants;
import com.tairanchina.md.meeting.constants.MeetingProvider;
import com.tairanchina.md.meeting.entity.YearMeetingTree;
import com.tairanchina.txRestFilter.engine.jersey.TxJerseyTools;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.util.Objects;

/**
 * Created by lxliuxuan on 2016/12/28.
 */
@Path("/rest/tree")
public class TreeResource {

    private Logger logger = LoggerFactory.getLogger(TreeResource.class);




    /**
     * 加速树的生长速度
     * @return
     */
    @PUT
    @Path("/advance")
    public Response advance(){

        try {
            YearMeetingTree tree = MeetingProvider.treeService.findTree();
            if(tree != null && tree.getTreeState() < tree.getEndState()){
                tree.setTreeState(tree.getTreeState()+1);
                MeetingProvider.treeService.updateTree(tree);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("加速树增长失败,e:{}",e);
        }

        return TxJerseyTools.returnSuccess();
    }

    /**
     * 修改树的自动生长开关
     */
    @GET
    @Path("/delay/{switch}")
    public Response delay(@PathParam("switch") String switchState){

        try {
            if(!checkState(switchState)){
                return TxJerseyTools.returnAbort(CommonConstants.ErrorCode.ERROR_ILLEGAL_PARAMTER);
            }
            YearMeetingTree tree = MeetingProvider.treeService.findTree();
            if(tree != null){
                tree.setSwitchState(switchState);
                MeetingProvider.treeService.updateTree(tree);
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error("修改树自动增长开关失败,e:{}",e);
        }
        return TxJerseyTools.returnSuccess();
    }

    private boolean checkState(String swicthState){
        if(StringUtils.isNotBlank(swicthState) ){
            if("on".equals(swicthState) || "off".equals(swicthState)){
                return true;
            }
        }
        return  false;
    }
}
